package com.example.java_gobang2.api;

import com.example.java_gobang2.game.Matcher;
import com.example.java_gobang2.game.OnlineUserManager;
import com.example.java_gobang2.model.MatchRequest;
import com.example.java_gobang2.model.MatchResponse;
import com.example.java_gobang2.model.User;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

@Slf4j
@Component
public class MatchAPI extends TextWebSocketHandler {
    @Autowired
    private Matcher matcher;
    @Autowired
    private OnlineUserManager onlineUserManager;
    private ObjectMapper objectMapper = new ObjectMapper();
    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        User user = (User) session.getAttributes().get("user");
        onlineUserManager.setGameHall(user.getUserId(), session);
        log.info("[MatchAPI]建立连接,userid:{}",user.getUserId());
    }

    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        User user = (User) session.getAttributes().get("user");
        MatchRequest request = objectMapper.readValue(message.getPayload(),MatchRequest.class);
        MatchResponse response = new MatchResponse();
        if (request.getMessage().equals("开始匹配")) {
            matcher.add(user);
            response.setMessage("开始匹配");
            log.info("开始匹配");
        }else if (request.getMessage().equals("停止匹配")) {
            matcher.remove(user);
            response.setMessage("停止匹配");
            log.info("停止匹配");
        }else if (request.getMessage().equals("人机对战匹配")) {
            matcher.addAI(user);
            response.setMessage("AI匹配成功");
            log.info("AI匹配成功");
        }
        session.sendMessage(new TextMessage(objectMapper.writeValueAsString(response)));
    }

    @Override
    public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
        super.handleTransportError(session, exception);
    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        super.afterConnectionClosed(session, status);
    }
}
